/*
 * Copyright (c) 2011 Joe Kopena <tjkopena@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.rocketshipgames.haxe;

import flash.display.Sprite;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.geom.Rectangle;

class Engine extends Sprite {

  private var _buffer:BitmapData;

  private var _width:Int;
  private var _height:Int;

  private var _prevFrameTimestamp:Int;
  private var _startTimestamp:Int;

  private var _layers:Array<List<Entity>>;

  public function new(width:Int, height:Int):Void
  {
    super();

    _layers = new Array();
    _layers[0] = new List();

    _width = Context.screenWidth = width;
    _height = Context.screenHeight = height;

    // Put us on the stage
    flash.Lib.current.addChild(this);

    _buffer = new BitmapData(_width, _height);
    addChild(new Bitmap(_buffer));

    Context.buffer = _buffer;
    Context.bufferRectangle = new Rectangle(0, 0,
					    _buffer.width, _buffer.height);

    stage.addEventListener(Event.ADDED_TO_STAGE, onStage);
    stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
    stage.addEventListener(KeyboardEvent.KEY_DOWN, Context.onKeyDown);
    stage.addEventListener(KeyboardEvent.KEY_UP, Context.onKeyUp);

    // end new
  }

  //------------------------------------------------------------
  public function add(entity:Entity, ?layer:Int=0)
  {
    trace("Received entity");

    entity.setParent(this);
    entity.layer = layer;

    if (layer < 0)
      return;

    while (_layers.length <= layer) {
      _layers.push(new List());
    }

    _layers[layer].add(entity);
    // end function add
  }

  public function setLayer(entity:Entity, ?layer:Int=0)
  {
    if (entity.layer >= 0 && entity.layer < _layers.length)
      _layers[entity.layer].remove(entity);

    entity.layer = layer;

    if (layer < 0)
      return;

    while (_layers.length <= layer) {
      _layers.push(new List());
    }

    _layers[layer].add(entity);
    // end function setLayer
  }

  public function remove(entity:Entity)
  {
    if (entity.layer >= 0 && entity.layer < _layers.length)
      _layers[entity.layer].remove(entity);
    // end function remove
  }

  //------------------------------------------------------------
  private function onStage(e:Event=null):Void
  {
    _startTimestamp = _prevFrameTimestamp = flash.Lib.getTimer();
    // end function onStage
  }

  //------------------------------------------------------------
  //------------------------------------------------------------
  private function onEnterFrame(e:Event=null):Void
  {
    var currTime:Int = flash.Lib.getTimer();

    Context.elapsed = currTime - _prevFrameTimestamp;
    Context.time = currTime - _startTimestamp;
    _prevFrameTimestamp = currTime;

    update();

    _buffer.lock();
    render();
    _buffer.unlock();
    // end function onEnterFrame
  }

  //------------------------------------------------------------
  private function update():Void
  {
    for (l in _layers)
      for (e in l)
	e.update();
    // end function update
  }

  //------------------------------------------------------------
  private function render():Void
  {
    for (l in _layers)
      for (e in l)
	e.render();
    // end function render
  }

  // end Engine
}
